package com.ftg.learn.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.math.Calculator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ftg.learn.system.dto.UserDto;
import com.ftg.learn.system.entity.User;
import com.ftg.learn.system.service.IUserService;
import com.ftg.learn.util.JsonWeb;
import com.ftg.learn.util.JsonWebUtil;
import com.ftg.learn.util.JwtUtil;
import com.ftg.learn.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author kangjx
 * @since 2023-04-26
 */
@Api(tags = "登陆模块")
@RestController
@RequestMapping("/api/system/user")
@CrossOrigin("http://192.168.1.4:9000")
public class UserController {

    @Resource
    IUserService iUserService;



    /**
     * 生成验证码功能
     */
    @GetMapping("/captcha")
    public void createCaptcha(HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(102, 38, 2, 1);
        captcha.setGenerator(new MathGenerator(1));
        captcha.createCode();
        captcha.write(response.getOutputStream());

        String verifyCode = captcha.getCode();

        //通过HUTOOL计算最终结果存储前端
        double result = Calculator.conversion(verifyCode);
        int resultInt = (int) result;

        //分布式系统不能直接使用session 存储|所以现在暂时采用cookie ，后期改成redis
        Cookie cookie=new Cookie("verifyCode",String.valueOf(resultInt));
        cookie.setPath("/");
        cookie.setMaxAge(3600);
        response.addCookie(cookie);

        response.getOutputStream().close();
    }

    @PostMapping("/login")
    @ApiOperation("登陆功能")
    public JsonWeb<String> checkUserNameWithPassword(@RequestBody UserDto user
    ){
        //初始状态
        final String freeze = "1";
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",user.getAccount());
        //md5 对加密一次
        queryWrapper.eq("User_password", MD5.encrypt2ToMD5(user.getPassword()));
        User userInfo = iUserService.getOne(queryWrapper);

        if(Objects.isNull(userInfo)){
            return JsonWebUtil.accountChecked(null);
        }else if(freeze.equals(userInfo.getIsDeleted())){
            return JsonWebUtil.build(500,"当前帐号已冻结！！！",null);
        }else{
            return JsonWebUtil.success(JwtUtil.createjwtToken(userInfo.getId(),user.getAccount()));
        }
    }

}
